﻿using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

namespace NTime
{
    public class NetTime
    {
        private string GetHttpWebRequest()
        {
            //Uri uri = new Uri("https://f.m.suning.com/api/ct.do");  //苏宁时间同步api
            //Uri uri = new Uri("http://api.pinduoduo.com/api/server/_stm");  //拼夕夕时间同步api  
            Uri uri = new Uri("http://192.168.2.200/api/ts/NowTime");  //拼夕夕api本地化后的api
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
            myReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36";
            myReq.Accept = "*/*";
            myReq.KeepAlive = true;
            myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
            HttpWebResponse result = (HttpWebResponse)myReq.GetResponse();
            Stream receviceStream = result.GetResponseStream();
            StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
            string strHTML = readerOfStream.ReadToEnd();
            readerOfStream.Close();
            receviceStream.Close();
            result.Close();
            return strHTML;
        }

        public DateTime getDT()
        {
            string GetTimeString = GetHttpWebRequest();
            JObject jo = JObject.Parse(GetTimeString);
            //string TimeString = jo["currentTime"].ToString();//苏宁api，json字段名
            string TimeString =jo["server_time"].ToString();//拼夕夕api，json字段名
            long time = long.Parse(TimeString) / 1000;//转换成秒
            DateTime dt = new DateTime(1970, 1, 1).AddSeconds(time);
            DateTime dt1 = dt.AddHours(8);    //+8转为中国时区
            return dt1;
        }
    }
}